<?php
namespace app\index\controller\xilujob;

use app\common\controller\xilujob\Xilujob;
use app\common\model\xilujob\EnterpriseInfo;
use app\common\model\xilujob\Job;
use app\common\model\xilujob\JobApply;
use app\common\model\xilujob\XilujobUser;
use app\common\model\xilujob\JobInterview AS JobInterviewModel;
use think\Exception;
use function fast\array_get;

class JobInterview extends Xilujob {

    protected $noNeedLogin = [];

    protected $noNeedRight = ['*'];

    protected $restrictedActions = [];

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->model = new JobInterviewModel();
    }

    public function index(){
        $this->relationSearch = true;
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $interviews = $this->model
                ->with([
                'resume',
                'job'=>function($query){$query->withField('id,job_name');}
            ])
                ->where('company_id', $this->company->id)
                ->where($where);
            $params = $this->request->get('');
            if($date=array_get($params,'date')) {
                $date = strtotime($date);
                $interviews->whereBetween('interview_time',[$date, $date+3600*24]);
            }

            $interviews->order($sort,$order);
            $lists = $interviews->paginate($limit);
            foreach($lists as $interview) {
                //fixme: tp5无法正常使用with嵌套预加载， 只能在循环中读取
                $interview->resume->relationQuery(['user','personal','personal_tags','summary','works']);
            }

            $result = array("total" => $lists->total(), "rows" => $lists->items());

            return json($result);
        }
        $this->assignconfig('jobs', Job::where('publisher_id',$this->company->id)->column('id,job_name as name'));
        $this->view->assign('title', '面试邀请');
        return $this->view->fetch();
    }

    /**
     *
     */
    public function create_interview() {
        $xilujobuser = XilujobUser::get(['user_id'=>$this->auth->id]);
        if($xilujobuser->enterprise_model->audit_status!=1) {
            $this->error('企业审核通过后方可邀请面试');
        }

        if($this->request->isPost()) {
            $params = $this->request->post('row/a');
            $params['company_id'] = $this->company->id;
            try {
                $ret = \app\common\model\xilujob\JobInterview::createInterview($params);
            }catch (Exception $exception){
                $this->error($exception->getMessage());
            }
            $this->success('', '', ['interview' => $ret]);
        }

        $applyId = $this->request->param('apply_id');
        $apply = JobApply::get($applyId);
        $job = $apply? [$apply->job]:null;
        $jobs = $job ? $job : Job::where('publisher_id', $this->company->id)
            ->where('status',Job::STATUS_ENABLED)
            ->field('id,job_name')
            ->select();

        $resumeId = $this->request->param('resume_id');
        $resume = \app\common\model\xilujob\Resume::get($resumeId);
        if(!$resume) {
            $this->error('参数错误');
        }
        $enterpriseInfo = EnterpriseInfo::get(['company_id'=>$this->company->id]);
        return $this->fetch('create_interview',[
            'apply'=>$apply, 'job'=>$job, 'jobs'=>$jobs, 'resume'=>$resume, 'enterprise_info'=>$enterpriseInfo
        ]);
    }

    public function batch_invite() {
        //$jobId = $this->request->param('job_id');
        //$job = $jobId ? Job::withTrashed()->where('publisher_id',$this->company->id)->find($jobId) : null;
        $resumeIds = $this->request->param('resume_ids');
        $applyIds = $this->request->param('apply_ids');
        $resumeIds = $resumeIds ? explode(',', $resumeIds) : [];
        $applyIds = $applyIds ? explode(',', $applyIds) : [];

        if($this->request->isPost()) {
            $params = $this->request->post('row/a');
            $params['company_id'] = $this->company->id;
            foreach ($resumeIds as $i => $resumeId) {
                $applyId = array_get($applyIds, $i);
                $params['apply_id'] = $applyId;
                $params['resume_id'] = $resumeId;
                $params['user_id'] = \app\common\model\xilujob\Resume::where('id', $resumeId)->value('user_id');
                try {
                    $ret = \app\common\model\xilujob\JobInterview::createInterview($params);
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            $this->success('');
        }

        $jobIds = $applyIds?JobApply::whereIn('id',$applyIds)->column('job_id'):[];

        $jobs = $jobIds ? Job::where('publisher_id', $this->company->id)
            ->where('status',Job::STATUS_ENABLED)
            ->whereIn('id',$jobIds)
            ->field('id,job_name')
            ->select() : Job::where('publisher_id', $this->company->id)
            ->where('status',Job::STATUS_ENABLED)
            ->field('id,job_name')
            ->select();
        $enterpriseInfo = EnterpriseInfo::get(['company_id'=>$this->company->id]);
        return $this->fetch('batch_invite',[
             'jobs'=>$jobs, 'enterprise_info'=>$enterpriseInfo
        ]);
    }

    /**
     *企业 改变面试状态
     */
    public function interview_status() {
        $interview = jobInterviewModel::get($this->request->post('interview_id'));
        if(!$interview) {
            $this->error(__('no record'));
        }
        $status = $this->request->post('status');
        if(in_array($status, [jobInterviewModel::STATUS_INTERVIEW_FAILED,jobInterviewModel::STATUS_INTERVIEW_PASSED])
            && $this->company->id!=$interview->company_id) {
            // 非目标企业
            $this->error(__('no record'));
        }
        $ret = jobInterviewModel::transitStatus($interview, $status);
        if(is_string($ret)) {
            $this->error($ret);
        }
        $this->success('', '', ['interview'=>$ret]);
    }

    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed   $searchfields   快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @return array
     */
    protected function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset", 0);
        $limit = $this->request->get("limit", 0);
        //新增自动计算页码
        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = $this->request->get("page/d", 1);
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $tableName = '';
        if ($relationSearch) {
            if (!empty($this->model)) {
                $name = \think\Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
                $tableName = $name . '.';
            }
            $sortArr = explode(',', $sort);
            foreach ($sortArr as $index => & $item) {
                $item = stripos($item, ".") === false ? $tableName . trim($item) : $item;
            }
            unset($item);
            $sort = implode(',', $sortArr);
        }

        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $tableName . $v : $v;
            }
            unset($v);
            $arrSearch = [];
            foreach (explode(" ", $search) as $ko) {
                $arrSearch[] = '%'.$ko.'%';
            }
            $where[] = [implode("|", $searcharr), "LIKE", $arrSearch];
        }

        foreach ($filter as $k => $v) {
            $sym = isset($op[$k]) ? $op[$k] : '=';


            // if($k == 'status') {
            //     if(!in_array($v, [JobInterviewModel::STATUS_INTERVIEW_SENT, JobInterviewModel::STATUS_INTERVIEW_REJECTED])) {
            //         $sym = 'IN';
            //         $v = [JobInterviewModel::STATUS_INTERVIEW_ACCEPTED, JobInterviewModel::STATUS_INTERVIEW_FAILED, JobInterviewModel::STATUS_INTERVIEW_PASSED];
            //     }
            // }

            if (stripos($k, ".") === false) {
                $k = $tableName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);

            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $where[] = "FIND_IN_SET('{$v}', " . ($relationSearch ? $k : '`' . str_replace('.', '`.`', $k) . '`') . ")";
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' time', $arr];
                    break;
                case 'LIKE':
                case 'LIKE %...%':
                    $where[] = [$k, 'LIKE', "%{$v}%"];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
        }
        $where = function ($query) use ($where) {
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        // dump($where);exit;
        return [$where, $sort, $order, $offset, $limit,$page];
    }


}